import axios from 'axios'

import type { AxiosInstance } from 'axios'
import type { CrvRequestInterceptor, CrvRequestConfig } from './type'

class CrvRequest {
  config: CrvRequestConfig
  instance: AxiosInstance
  interceptors?: CrvRequestInterceptor
  constructor(cg: CrvRequestConfig) {
    this.config = cg
    if (cg.headers) {
      cg.headers['x-forwarded-for'] =localStorage.getItem('source-ip')??''
    }
    this.instance = axios.create(cg)
    this.interceptors = cg.crvInterceptors

    // 1.从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.resposeInterceptor,
      this.interceptors?.resposeInterceptorCatch
    )

    //2:全局拦截
    this.instance.interceptors.request.use(
      (config) => {
        return config
      },
      (error) => {
        return error
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        return res
      },
      (error) => {
        // console.log('所有实例拦截到的响应出错', error)
        return error
      }
    )
  }
  //1:请求函数
  public request<T>(config: CrvRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      //1:具体请求的拦截
      if (config.crvInterceptors?.requestInterceptor) {
        config = config.crvInterceptors.requestInterceptor(config)
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.crvInterceptors?.resposeInterceptor) {
            res = config.crvInterceptors.resposeInterceptor(res)
          }
          resolve(res)
        })
        .catch((error) => {
          if (config.crvInterceptors?.resposeInterceptorCatch) {
            config.crvInterceptors.resposeInterceptorCatch(error)
          }
          reject(error)
        })
    })
  }

  //2:get请求函数
  public get<T>(config: CrvRequestConfig<T>) {
    return this.request<T>({ ...config, method: 'GET' })
  }

  //3:post请求函数
  public post<T>(config: CrvRequestConfig<T>) {
    return this.request<T>({ ...config, method: 'POST' })
  }

  //4:delete请求函数
  public delete<T>(config: CrvRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }

  //5:patch请求函数
  public patch<T>(config: CrvRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}



export default CrvRequest
